package com.intellekt.ecert.users.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.CannotGetJdbcConnectionException;

import com.intellekt.ecert.domain.SuperAction;
import com.intellekt.ecert.users.service.UsersService;
import com.intellekt.ecert.users.vo.ItemVO;

public class ItemsAsyncAction extends SuperAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7017252015770984952L;
	private static final Logger log = Logger.getLogger(ItemsAsyncAction.class);

	@Autowired
	private UsersService service;

	private String jsonrecords;
	private String username;
	private String idTipoCertificado;
	private String idMercancia;

	public String mercanciasUsername() throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("mercanciasUsername...");
		}

		boolean success = true;
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		try {
			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();

			List<ItemVO> list = (List<ItemVO>) service.getItemsByUser(username);

			for (ItemVO tmp : list) {
				Map<Object, Object> map = new HashMap<Object, Object>();

				map.put("act", tmp.isActivo());
				map.put("id", tmp.getId());
				map.put("desc", tmp.getDesc());
				map.put("scien", tmp.getScien());
				map.put("nuevo", false);
				map.put("modificado", false);
				map.put("eliminado", false);
				map.put("username", username);

				mapResult.add(map);
			}

			resultSet.put("Result", mapResult);
			messages.put("ResultSet", resultSet);

		} catch (CannotGetJdbcConnectionException e) {
			e.printStackTrace();
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, "La base de datos de VUCEM no esta disponible, intente mas tarde");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			streamIt(messages);
		}

		return STREAM;
	}

	public String mercanciasPorTipoCertificado() throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("mercancias");
		}

		boolean success = true;
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		try {
			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();

			List<ItemVO> list = (List<ItemVO>) service.getItemsByTransactionId(idTipoCertificado, username);

			for (ItemVO tmp : list) {
				Map<Object, Object> map = new HashMap<Object, Object>();

				map.put("act", tmp.isActivo());
				map.put("id", tmp.getId());
				map.put("desc", tmp.getDesc());
				map.put("scien", tmp.getScien());
				map.put("nuevo", false);
				map.put("modificado", false);
				map.put("eliminado", false);

				mapResult.add(map);
			}

			resultSet.put("Result", mapResult);
			messages.put("ResultSet", resultSet);

		} catch (CannotGetJdbcConnectionException e) {
			e.printStackTrace();
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, "La base de datos de VUCEM no esta disponible, intente mas tarde");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			streamIt(messages);
		}

		return STREAM;
	}

	public String mercanciasPorId() throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("mercanciasPorId");
		}

		boolean success = true;
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		try {
			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();

			
			//String ids[] = StringUtils.split(idMercancia, ",");
			
			List<ItemVO> list = (List<ItemVO>) service.getItemsById(idMercancia, username);

			for (ItemVO vo: list) {
				if (vo != null) {
					Map<Object, Object> map = new HashMap<Object, Object>();

					map.put("act", vo.isActivo());
					map.put("id", vo.getId());
					map.put("desc", vo.getDesc());
					map.put("scien", vo.getScien());
					map.put("nuevo", false);
					map.put("username", vo.getUsername());
					map.put("modificado", false);
					map.put("eliminado", false);
					mapResult.add(map);
				}
			}

			resultSet.put("Result", mapResult);
			messages.put("ResultSet", resultSet);

		} catch (CannotGetJdbcConnectionException e) {
			e.printStackTrace();
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, "La base de datos de VUCEM no esta disponible, intente mas tarde");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			streamIt(messages);
		}

		return STREAM;
	}

	public String guardarMercancia() throws Exception {

		if (log.isDebugEnabled()) {
			log.debug("guardarMercancia..."+jsonrecords);
		}

		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		boolean success = true;

		try {

			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();

			List<ItemVO> lista = parseJson(jsonrecords);
			log.debug("lista..." + lista.size());
			service.saveItems(lista);

			resultSet.put("Result", mapResult);
			messages.put("ResultSet", resultSet);

		} catch (Exception e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			streamIt(messages);
		}

		return STREAM;

	}

	@SuppressWarnings("rawtypes")
	private final List<ItemVO> parseJson(String jsonString) throws RuntimeException {
		try {

			List<ItemVO> registros = new ArrayList<ItemVO>();

			if (jsonString != null) {
				JSONArray jsonArray = JSONArray.fromObject(jsonString);
				if (log.isDebugEnabled()) {
					log.debug("jsonArray.size() = > [ " + jsonArray.size() + " ]");
				}
				boolean nuevo = false;
				boolean modificado = false;
				boolean activo = false;
				boolean eliminado = false;
				String id, desc, scien, username;

				ItemVO tmp = null;
				Iterator it = jsonArray.iterator();
				while (it.hasNext()) {
					JSONObject jsonObject = (JSONObject) it.next();

					nuevo = super.parseJsonBoolean(jsonObject, "nuevo");
					modificado = super.parseJsonBoolean(jsonObject, "modificado");
					eliminado = super.parseJsonBoolean(jsonObject, "eliminado");

					if (modificado == true || nuevo == true || eliminado == true) {
						id = parseJsonString(jsonObject, "id");
						desc = parseJsonString(jsonObject, "desc");
						scien = parseJsonString(jsonObject, "scien");
						username = parseJsonString(jsonObject, "username");

						tmp = new ItemVO();
						tmp.setId(id);
						tmp.setDesc(desc);
						tmp.setScien(scien);
						tmp.setUsername(username);
						tmp.setEliminado(eliminado);
						tmp.setNuevo(nuevo);
						registros.add(tmp);

					}

				}
			}

			return registros;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String getJsonrecords() {
		return jsonrecords;
	}

	public void setJsonrecords(String jsonrecords) {
		this.jsonrecords = jsonrecords;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getIdTipoCertificado() {
		return idTipoCertificado;
	}

	public void setIdTipoCertificado(String idTipoCertificado) {
		this.idTipoCertificado = idTipoCertificado;
	}

	public String getIdMercancia() {
		return idMercancia;
	}

	public void setIdMercancia(String idMercancia) {
		this.idMercancia = idMercancia;
	}
}
